<template>
  <div class="container"
       :style="note">
    <!-- 登录头部 -->
    <header-term @headRegister="headRegister" />
    <div class="box">
      <div v-if="!passwordBox">
        <div class="identification">
          <img class="info-img"
               src="@/static/images/d_logo.png">
        </div>
        <div v-if="!enroll"
             key="login">
          <el-tabs v-model="activeName"
                   class="logo-tab"
                   @tab-click="handleClick">
            <el-tab-pane label="密码登录"
                         name="password">
              <password-login :loading="loading"
                              :alias="alias"
                              @login="login" />
            </el-tab-pane>
            <el-tab-pane label="短信登录"
                         name="phone">
              <div class="tips">只支持管理员用户</div>
              <phone-login :loading="loading"
                           @login="login" />
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- 注册 -->
        <div v-else
             key="enroll">
          <enroll :enroll.sync="enroll" />
        </div>
        <div :style="enrollBoxStyle"
             :class="enrollBoxClass">
          <el-link v-if="isActiveName"
                   :underline="false"
                   @click="passwordBox = true">忘记密码</el-link>
          <div class="centerSty">
            <span class="enroll-hand">{{enroll ? '已有账号，' : '没有账号？'}}</span>
            <transition name="fade"
                        mode="out-in">
              <el-link :underline="false"
                       @click="enrollClick">{{enroll ? '登录' : '立即注册'}}</el-link>
            </transition>
          </div>
        </div>
      </div>
      <forget-password v-if="passwordBox"
                       @back="toLogin" />
      <!-- </transition> -->
    </div>
    <div class="version-content">Copyright©2022 上海南软信息科技有限公司版权所有 沪ICP备15052516号-1</div>
    <!-- <span>{{compileTime}}</span> -->
    <!-- 扫码 -->
    <!-- <span style="position:absolute;right:0;bottom:0">20220713-1</span> -->
  </div>
</template>

<script>
import Enroll from '@/views/enroll/Index'
import { mapActions } from "vuex";
import PasswordLogin from './loginMode/PasswordLogin.vue'
import PhoneLogin from './loginMode/PhoneLogin.vue'
import ForgetPassword from './loginMode/ForgetPassword.vue'
import headerTerm from '@/components/head/Head'
import { loadMenuTree } from '@menu'

function resetfirstTagsView (tree) {
  if (!tree) return
  tree.meta = { isAffix: true }
  if (!tree.children || tree.children.length === 0) {
    const { url, index } = tree
    return url === '/' ? { ...tree, url: index } : tree
  } else {
    return resetfirstTagsView(tree.children[0]);
  }
}

export default {
  name: "Login",
  components: { Enroll, PasswordLogin, PhoneLogin, ForgetPassword, headerTerm },
  data () {
    return {
      loading: false,
      enroll: false,
      passwordBox: false,
      activeName: 'password',
      data: {
        username: null,
        password: null
      },
      alias: '',
      defaultRedirectUrl: '',
      note: {
        width: '100%',
        height: '100%',
        backgroundImage: "url(" + require("../static/images/back.jpg") + ")",
        backgroundSize: 'cover',
        position: 'relative'
      }
    };
  },
  computed: {
    // ...mapState({
    //   menu: (state) => state.menu.menu
    // }),
    title () {
      return this.enroll ? '用户注册' : '用户登录'
    },
    enrollBoxStyle () {
      return this.enroll ? 'justify-content:center' : 'justify-content:space-between';
    },
    enrollBoxClass () {
      return this.activeName === 'password' ? 'enroll-box' : 'enroll-box1';
    },
    isActiveName () {
      return this.activeName === 'password' && !this.enroll
    }
  },
  mounted () {
    this.data.username = this.$storage.read("LOGIN::username");
    this.getUrlAlias()
  },
  methods: {
    ...mapActions({
      loginOnly: "login/login",
      exportCount: "login/exportCount",
      getSystemBillDate: "login/getSystemBillDate",
      cleanDeviceTrace: "deviceTrace/cleanDeviceTrace",
      resetTagsView: "tagsView/resetTagsView",
      clearFirstNewRecordSearch: "table/clearFirstNewRecordSearch",
      clearRmsNewRecordSearch: "rmsTable/clearRmsNewRecordSearch",
      clearSearchPageSize: "pageSize/clearSearchPageSize"
    }),
    headRegister () {
      this.enroll = true
    },
    async handleSucceed () {
      this.$message({
        message: "登录成功",
        type: "success",
      });
      this.initializeInfo()
    },
    toLogin (val) {
      this.passwordBox = val
    },
    async login (form) {
      this.data = this.activeName === 'password' && form
      const username = this.alias ? `${form.username}@${this.alias}` : form.username

      let data = {
        username: username || null,
        password: form.password ? this.$md5(form.password) : null,
        mobile: form.mobile || null,
        code: form.code || null,
        activeName: this.activeName
      };
      this.loading = true
      let response = await this.loginOnly(data)
      if (response?.code === 0) {
        this.handleSucceed(response.data);
      } else {
        this.loading = false
        if (response) {
          this.$message({
            message: response.message,
            type: "warning",
          });
        }
        return
      }
    },
    getUrlAlias () {
      const url = window.location.href;
      let urlParams = url.split('?')[1];
      if (urlParams) {
        let params = new URLSearchParams(urlParams);
        this.alias = window.atob(params.get('alias'));
      }
    },
    getRedirectUrl () {
      let url = this.$storage.read("LOGIN::redirectUrl");
      if (url) {
        return url;
      }
      url = "/";
      return url;
    },
    redirectTo (url) {
      this.loading = false
      if (!url) {
        url = this.getRedirectUrl();
      }
      this.$storage.write("LOGIN::username", this.data.username);
      if (this.rememberMe) {
        // TODO: 实现记住密码逻辑
      }
      this.$router.replace({ path: this.defaultRedirectUrl })
    },
    handleClick (tab) {
      this.activeName = tab.name
    },
    enrollClick () {
      this.enroll = !this.enroll
    },
    async initializeInfo () {
      //初始化tags页签
      const tree = await loadMenuTree();
      let result = resetfirstTagsView(tree[0])
      this.defaultRedirectUrl = result?.url
      const user = sessionStorage.getItem('userInfo')
      const userParse = JSON.parse(user)
      this.resetTagsView({ userId: userParse?.userId, resets: [result] })
      //初始化搜索条件 报表
      this.clearRmsNewRecordSearch(userParse?.userId)
      //初始化搜索条件
      this.clearFirstNewRecordSearch(userParse?.userId)
      this.clearSearchPageSize(userParse?.userId)
      this.redirectTo();
      this.cleanDeviceTrace({});
    }
  },
};
</script>

<style scoped>
.container {
  /* width: 100%;
  height: 100%;
  background-image: url("~@/static/images/back.png");
  background-size: cover;
  position: relative; */
}
.version-content {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: center;
  position: absolute;
  /* left: 50%; */
  bottom: 0px;
  /* transform: translate(-50%, -50%); */
  color: var(--prev-bg-white);
  font-size: 14px;
  background-color: rgba(0, 0, 0, 0.4);
  /* right: 0;
  bottom: 0; */
}
.logo-tab >>> .el-tabs__header {
  padding-bottom: 10px !important;
}
.logo-tab >>> .el-tabs__nav {
  width: 100%;
  text-align: center;
}
.logo-tab >>> .el-tabs__active-bar {
  /* left: 39px; */
  left: 39px !important;
}
.logo-tab >>> .el-tabs__item {
  padding: 0 40px !important;
  /* color: var(--prev-border-color-lightgrey) !important; */
}
.logo-tab >>> .el-tabs__nav-wrap::after {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 0;
  height: 0px;
}

.identification {
  height: 110px;
  position: relative;
}
.info-img {
  position: absolute;
  top: 52%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.enroll-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
}
.enroll-box1 {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 12px;
}
.enroll-hand {
  font-size: 14px;
  color: var(--prev-border-color-lightgrey);
}
.box {
  width: 350px;
  min-height: 428px;
  padding: 20px 45px 12px 45px;
  background: var(--prev-bg-white);
  box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
  opacity: 1;
  border-radius: 10px;
  position: absolute;
  top: 52%;
  left: 50%;
  transform: translate(-50%, -50%);
}

label.el-checkbox.rememberme {
  margin: 0px 0px 15px;
  text-align: left;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}

/* 可以设置不同的进入和离开动画 */
/* 设置持续时间和动画函数 */
.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */ {
  transform: translateX(10px);
  opacity: 0;
}
.centerSty {
  display: flex;
  justify-content: center;
  align-items: center;
}
.extensionContent {
  width: 36px;
  height: 84px;
  background: var(--prev-bg-white);
  box-shadow: 0px 3px 6px rgb(0 0 0 / 16%);
  border-radius: 5px;
  z-index: 9999;
  padding: 15px 6px;
  font-size: 12px;
  float: right;
  margin-top: 36%;
  margin-right: 10px;
}
.extensionIcon {
  width: 19.52px;
  height: 19.52px;
}
.centerSty {
  display: flex;
  justify-content: center;
  align-items: center;
}
.aroundSty {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.contSty {
  padding: 10px 10px 0 10px;
}
.borderSty {
  height: 0px;
  border: 1px dashed var(--prev-border-color-grey);
  opacity: 1;
  margin: 10px 0;
}
.width136 {
  width: 136px;
}
.width281 {
  width: 281px;
}
.mt4 {
  margin-top: 4px;
}
.mt10 {
  margin-top: 10px;
}
.tips {
  font-size: 12px;
  margin-bottom: 5px;
  color: var(--prev-border-color-lightgrey);
}
</style>